const db = require('../db/index')
const bcrypt = require('bcryptjs')
// 获取维修员个人信息
exports.getMaintainerInfo = (req, res) => {
    const  id  = req.user.id
    sql = 'select * from maintainer where id =?'
    db.query(sql, id, (err, result) => {
        if (err) return res.cc(err)
        if(result.length === 0)return res.cc('未查询到用户信息')
        result[0].password = ''
        res.send({
            status: 0,
            message:'查询成功',
            data: result[0]
        })
    })
}

// 维修记录
exports.getMaintainList = (req, res) => {
    const  id  = req.user.id
    const sql = `SELECT
    o.id,
	o.appointmentDate,
	o.startTime,
    o.endTime,
    o.linkman,
    o.phone,
	o.failure,
    o.order_status,
	o.create_time,
	o.take_time,
	o.done_time,
	o.maintainer_id,
    o.remark,
    o.service_pice as 'material_pice',
    o.material_maintain,
	m.nickname as'maintainer_nickname',	
	m.phone as 'maintainer_phone',
	s.service_name,
	s.service_img,
	s.service_pice,
	a.districts,
	a.city,
	a.county,
	a.full_address
FROM
	orderinfo o,
	maintainer m,
	repair_service s,
  address a
WHERE
	o.maintainer_id = ?
AND
	o.serviceAddress = a.id
AND
 (o.maintainer_id = m.id OR o.maintainer_id IS NULL)
AND
	o.service_id = s.id
ORDER BY
    o.order_status,
    o.id DESC
`
    db.query(sql, id, (err, result) => {
        if (err) return res.cc(err)
        if(result.length === 0) return res.cc('未查询到订单信息')
        res.send({
            status: 0,
            message:'查询成功',
            data: result
        })
    })
}

// 接单列表
exports.takeOrderList = (req, res) => {
    const sql = `SELECT
	o.id,
    o.linkman,
	o.appointmentDate,
	o.startTime,
    o.endTime,
    o.phone,
	o.failure,
    o.order_status,
	o.create_time,
	o.take_time,
	o.done_time,
	o.maintainer_id,
    o.remark,
	s.service_name,
	s.service_img,
	s.service_pice,
	a.districts,
	a.city,
	a.county,
	a.full_address
FROM
	orderinfo o,
	maintainer m,
	repair_service s,
    address a
WHERE
	o.maintainer_id IS NULL
AND
	o.serviceAddress = a.id
AND
    o.order_status = 1
AND
	o.service_id = s.id
GROUP BY o.id
ORDER BY
    o.id DESC
`
    db.query(sql,  (err, result) => {
        if (err) return res.cc(err)
        if(result.length === 0) return res.cc('未查询到订单信息')
        res.send({
            status: 0,
            message:'查询成功',
            data: result
        })
    })
}

// 特邀订单
exports.AssignTakeOrder = (req, res) => {
    const  id  = req.user.id
    const sql = `SELECT
	o.id,
    o.linkman,
	o.appointmentDate,
	o.startTime,
    o.endTime,
    o.phone,
	o.failure,
    o.order_status,
	o.create_time,
	o.take_time,
	o.done_time,
	o.maintainer_id,
    o.remark,
	s.service_name,
	s.service_img,
	s.service_pice,
	a.districts,
	a.city,
	a.county,
	a.full_address
FROM
	orderinfo o,
	maintainer m,
	repair_service s,
    address a
WHERE
	o.maintainer_id =?
AND
	o.serviceAddress = a.id
AND
    o.order_status = 1
AND
	o.service_id = s.id
GROUP BY o.id
ORDER BY
    o.id DESC
`
    db.query(sql, id, (err, result) => {
        if (err) return res.cc(err)
        if(result.length === 0) return res.cc('未查询到订单信息',0)
        
        res.send({
            status: 0,
            message:'查询成功',
            data: result
        })
    })
}

// 上传头像
exports.uploadAvatar = (req, res) => {
    const sql = 'update maintainer set avatar=? where id=?'
    // const avatar = path.join('../uploads', req.file.filename)
    db.query(sql, [req.body.avatar, req.user.id], (err, results) => {
        if(err) return res.cc(err)
        // console.log(results)
        if(results.affectedRows !== 1) return res.cc('上传头像失败')
        res.cc('上传头像成功', 0)
    })
}

// 接单确认
exports.confirmOrder = (req, res) =>{
    const sql = 'update orderinfo set maintainer_id=?,take_time=?, order_status= 2  where id=?'
    db.query(sql, [req.user.id,new Date().toLocaleString(), req.body.id], (err, results) => {
        if(err) return res.cc(err)
        if(results.affectedRows !== 1) return res.cc('接单失败')
        res.cc('接单成功', 0)
    })
}

// 维修完成
exports.updateOrder = (req, res) =>{
    const obj = req.body
    if(req.body.order_status === 4)
        obj.done_time =  new Date().toLocaleString()
    else
        obj.done_time = null

    const sql = `
    update 
        orderinfo 
    set 
        order_status=?, 
        service_pice=?,
        material_maintain=?,
        done_time=? 
    where 
        id=?`
        db.query(sql, [obj.order_status, obj.service_pice, obj.material_maintain, obj.done_time, obj.id], (err, results) => {
            if(err) return res.cc(err)
            if(results.affectedRows !== 1) return res.cc('更新失败')
            res.cc('更新成功', 0)
        })
}

// 查询维修员评分
exports.getScore = (req, res) => {
    let sql = 'select count(score) as "lowScore" from orderinfo where maintainer_id= ? AND score < 3 AND order_status >= 4'
    db.query(sql, req.user.id, (err, results) => {
        if(err) return res.cc(err)
        if(results.length === 0) return res.cc('未查询到评分信息', 0)
        let lowScore = results[0].lowScore
    sql = 'select count(score) as "middleScore" from orderinfo where maintainer_id= ? AND score = 3 AND order_status >= 4'
    db.query(sql, req.user.id, (err, results) => {
        if(err) return res.cc(err)
        if(results.length === 0) return res.cc('未查询到评分信息', 0)
        let middleScore = results[0].middleScore
        sql = 'select count(score) as "highScore" from orderinfo where maintainer_id= ? AND score > 3 AND order_status >= 4'
        db.query(sql, req.user.id, (err, results) => {
            if(err) return res.cc(err)
            if(results.length === 0) return res.cc('未查询到评分信息', 0)
            let highScore = results[0].highScore
            res.send({
                status: 0,
                message: '查询成功',
                data: {
                    total: lowScore + middleScore + highScore,
                    lowScore,
                    middleScore,
                    highScore
                    }
                })
            })
        })
    })
}

// 修改维修员信息
exports.updateInfo = (req, res) => {
    const sql = 'update maintainer set ? where id=?'
    db.query(sql, [req.body, req.user.id], (err, results) => {
        if(err) return res.cc(err)
        if(results.affectedRows !== 1) return res.cc('修改失败')
        res.cc('修改成功', 0)
    })
}

// 修改密码
exports.updatePwd = (req, res) => {
     const { oldPwd, newPwd } = req.body
    const selectSql = 'select password from maintainer where id=?'
    db.query(selectSql, req.user.id, (err,results) => {
        if(err) return res.cc(err)

        if(results.length !== 1) return res.cc('用户不存在')

        // TODO1：判断密码是否正确----bcrypt.compareSync(用户提交的密码, 数据库的密码)
        const compareResults = bcrypt.compareSync(oldPwd, results[0].password)
        if(!compareResults) return res.cc('修改失败，原密码错误')

        // 对密码进行加密
        const password = bcrypt.hashSync(newPwd, 10)

        const sql = 'update maintainer set password=? where id=?'
        db.query(sql, [password, req.user.id], (err, results) => {
            if(err) return res.cc(err)

            // console.log(results);
            if(results.affectedRows !== 1) return res.cc('修改密码失败') 
            res.cc('修改密码成功',0)
        })
    })
}